package logic

import (
	"context"
	"errors"
	"fmt"
	"os"
	"videoProject/common/checkx"

	"videoProject/src/filemanage/rpc/file"
	"videoProject/src/filemanage/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadFileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileLogic {
	return &UploadFileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UploadFileLogic) UploadFile(in *file.UploadFileRequest) (*file.UploadFileResponse, error) {
	// todo: add your logic here and delete this line
	if checkx.PathExists(l.svcCtx.Config.Path, true) == false {
		l.Logger.Error("UploadFile file directory failed")
		return nil, errors.New(fmt.Sprintf("UploadFile file directory failed"))
	}
	url := l.svcCtx.Config.Path + in.FileName

	logx.Info("UploadFile............" + url)
	fmt.Println("As string:", string(in.Content))
	err := os.WriteFile(url, in.Content, os.ModePerm)

	if err != nil {
		return &file.UploadFileResponse{
			Success: false,
			Message: err.Error(),
		}, err
	}
	return &file.UploadFileResponse{
		Success: true,
		Message: "File uploaded successfully " + in.FileName,
	}, nil
}
